Page({
  /**
   * 页面的初始数据
   */
  data: {
    feedbackList: [],
    userId: "",
    totalPages: 1,
    currentPage: 1,
    isLoading: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取用户ID
    const userInfo = wx.getStorageSync("userInfo");
    if (userInfo && userInfo.userId) {
      this.setData({
        userId: userInfo.userId,
      });
      this.getFeedbackList();
    } else {
      wx.showToast({
        title: "请先登录",
        icon: "none",
        success: () => {
          setTimeout(() => {
            wx.navigateTo({
              url: "/pages/login/login",
            });
          }, 1500);
        },
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 当页面显示时刷新反馈列表
    this.setData({
      currentPage: 1,
      feedbackList: [],
    });
    this.getFeedbackList();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      currentPage: 1,
      feedbackList: [],
    });
    this.getFeedbackList().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.currentPage < this.data.totalPages && !this.data.isLoading) {
      this.setData({
        currentPage: this.data.currentPage + 1,
      });
      this.getFeedbackList(true);
    }
  },

  /**
   * 获取反馈列表
   */
  getFeedbackList: function (isLoadMore = false) {
    const app = getApp();
    if (this.data.isLoading) return Promise.resolve();

    this.setData({ isLoading: true });

    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: isLoadMore ? "加载更多..." : "加载中...",
      });

      wx.request({
        url: "https://smartsound.top/api/feedback/v1/list",
        method: "GET",
        data: {
          user_id: this.data.userId,
          page: this.data.currentPage,
          page_size: 10,
        },
        success: (res) => {
          wx.hideLoading();
          if (res.data && res.data.code === 0) {
            let feedbackList = res.data.feedback_list || [];

            // 格式化每个反馈的时间
            feedbackList = feedbackList.map((item) => {
              if (item.submit_time) {
                item.submit_time = this.formatTime(item.submit_time);
              }
              return item;
            });

            const newList = isLoadMore
              ? this.data.feedbackList.concat(feedbackList)
              : feedbackList;

            this.setData({
              feedbackList: newList,
              totalPages: res.data.total_pages || 1,
            });
            resolve();
          } else {
            wx.showToast({
              title: "获取反馈列表失败",
              icon: "none",
            });
            reject();
          }
        },
        fail: (err) => {
          wx.hideLoading();
          wx.showToast({
            title: "网络错误，请稍后重试",
            icon: "none",
          });
          console.error("获取反馈列表失败", err);
          reject();
        },
        complete: () => {
          this.setData({ isLoading: false });
        },
      });
    });
  },

  /**
   * 格式化时间，去掉T并保持日期时间格式
   */
  formatTime: function (timeStr) {
    if (!timeStr) return "";

    // 替换T为空格
    return timeStr.replace("T", " ");
  },

  /**
   * 查看反馈详情
   */
  viewFeedbackDetail: function (e) {
    const feedbackId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/feedback/feedback_detail/feedback_detail?feedback_id=${feedbackId}&user_id=${this.data.userId}`,
    });
  },

  /**
   * 提交新反馈
   */
  goToSubmitFeedback: function () {
    wx.navigateTo({
      url: "/pages/feedback/feedback_submit/feedback_submit",
    });
  },

  /**
   * 返回上一页
   */
  navigateBack: function () {
    wx.navigateBack();
  },

  /**
   * 编辑反馈
   */
  editFeedback: function (e) {
    const feedbackId = e.currentTarget.dataset.id;
    console.log("编辑反馈ID:", feedbackId);

    // 从feedbackList中找到对应的反馈
    const feedback = this.data.feedbackList.find(
      (item) => String(item.feedback_id) === String(feedbackId)
    );

    if (feedback) {
      // 如果状态是已处理或已回复，则不允许编辑
      if (feedback.status === "已回复") {
        wx.showToast({
          title: "已回复的反馈不能编辑",
          icon: "none",
        });
        return;
      }

      console.log("准备编辑的反馈:", feedback);
      wx.navigateTo({
        url: `/pages/feedback/feedback_submit/feedback_submit?edit=true&feedback_id=${feedbackId}`,
      });
    } else {
      console.log("未找到反馈，feedbackList:", this.data.feedbackList);
      wx.showToast({
        title: "未找到该反馈",
        icon: "none",
      });
    }
  },

  /**
   * 获取状态标签样式
   */
  getStatusClass: function (status) {
    if (status === "未处理") {
      return "status-pending"; // 红色
    } else if (status === "处理中" || status === "已回复") {
      return "status-replied"; // 蓝色
    } else {
      return "status-pending"; // 默认红色
    }
  },
});
